#include <stdio.h>
#include <time.h>
#include <assert.h>
#include "include/array_generator.h"

int Search(int key, int arr[], int len) {
    for (int i = 0; i < len; i++) 
        if (arr[i] == key)
            return i;

    return -1; 
}

void testSearch() {
    time_t start = time(NULL); 
    for( int i = 0; i < 100000; i++) {
        int len = 100; 
        int key = 100; 
        int arr[len];
        GenOrderedArray(arr, len); 
        int index = Search(key, arr, len); 
        assert(index == -1);
        key = 99; 
        index = Search(key, arr, len); 
        assert(index == 99); 
    }
    time_t end = time(NULL); 
    printf("Time taken: %f seconds\n", difftime(end, start));
}

// 支持适配不同类型的数据结构，泛型编程， 在C语言中， 适配不同类型，可以通过void* 指针来实现
void* SearchGeneric(void* key, void* base, int n, int size, int (*compare)(void*, void*)); 

void* SearchGeneric(void* key, void* base, int n, int size, int (*compare)(void*, void*)) {
    for (int i = 0; i < n; i++) {
        void* elemAddr = (char*)base + i * size; 
        if (compare(key, elemAddr) == 0) {
            return elemAddr; 
        }
    }
    return NULL; 
}

int CompareInt(void* a, void* b) {
    return *(int*)a - *(int*)b; 
}

void testSearchGeneric() {
    int len = 10000;
    int key = 10000;
    int arr[len];
    GenOrderedArray(arr, len); 
    
    void* elem = SearchGeneric(&key, arr, len, sizeof(int), CompareInt);
    assert(elem == NULL);
    if (elem)  printf("found: %d\n", *(int*)elem); 
    else printf("not found\n");
    
    key = 9999; 
    elem = SearchGeneric(&key, arr, len, sizeof(int), CompareInt);
    if (elem)  printf("found: %d\n", *(int*)elem); 
    else printf("not found\n");
    assert(*(int*)elem == 9999); 
}

int main(int argc, char *argv[]) {
    testSearchGeneric(); 
    return 0; 
}